﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Drawing.Drawing2D;
using System.Net;
using System.Reflection;
using System.IO;
using System.Runtime.InteropServices;

namespace Locadora.BLL
{
    public class YouTubeBLL
    {
        string current_working_directory = @"c:\temp\"; // This is used to determine where to save the video.
        string youtube_video_title = "video"; // This gets set near the end of get_download_url()

        string nomeArquivo;

        public string NomeArquivo
        {
            get { return nomeArquivo; }
            set { nomeArquivo = value; }
        }


        public YouTubeBLL(string url, string titulo, string caminho)
        {
            if (caminho!="")
                current_working_directory = caminho;

            string youtube_url = makeYouTubeURLCompliant(url); // This makes the URL compliant with the code.
            string download_url = get_download_url(youtube_url, titulo); // This extracts the download URL from the YouTube website HTMl source code.
            download_video_from_url(download_url); // This actually downloads the video. I haven't tested this as I used someone elses queue download class for my own downloading needs.

        }

 

        public string get_download_url(string url, string titulo)
        {
            string download_url = null;
            string buffer = getYouTubePageContent(url);
           
            if (buffer.IndexOf("Error:") < 0)
            {
                int start = 0, end = 0;
                string startTag = "/watch_fullscreen?";
                string endTag = ";";
                start = buffer.IndexOf(startTag, StringComparison.CurrentCultureIgnoreCase);
                end = buffer.IndexOf(endTag, start, StringComparison.CurrentCultureIgnoreCase);
                string str = buffer.Substring(start + startTag.Length, end - (start + startTag.Length));
                string vid = str.Substring(str.IndexOf("video_id"), str.IndexOf("&", str.IndexOf("video_id")) - str.IndexOf("video_id"));
                string l = str.Substring(str.IndexOf("&l"), str.IndexOf("&", str.IndexOf("&l") + 1) - str.IndexOf("&l"));
                string t = str.Substring(str.IndexOf("&t"), str.IndexOf("&", str.IndexOf("&t") + 1) - str.IndexOf("&t"));
                string title = str.Substring(str.IndexOf("&title=") + 7);

                download_url = "http://youtube.com/get_video?" + vid + l + t;
            }

            else
            {
                new Exception("Error downloading video");
            }

            youtube_video_title = titulo;

            return download_url;
        }


        private string makeYouTubeURLCompliant(string url)
        {
                url = url.Replace("www.youtube.com", "youtube.com");

                if (url.IndexOf("http://youtube.com/v/") >= 0)
                {
                        url.Replace("http://youtube.com/v/", "http://youtube.com/watch?v=");
                }
                   
                if (url.IndexOf("http://youtube.com/watch?v=") < 0)
                {
                        url = "";
                }

                return (url);
        }


        // This is a helper method is used by get_download_url()

        private string getYouTubePageContent(string url)
        {

            string buffer;
            try
            {
                string outputBuffer = "where=46038";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentLength = outputBuffer.Length;
                req.ContentType = "application/x-www-form-urlencoded";
                StreamWriter swOut = new StreamWriter(req.GetRequestStream());
                swOut.Write(outputBuffer);
                swOut.Close();
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                buffer = sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception exp)
            {
                buffer = "Error: " + exp.Message.ToString();
            }

            return (buffer);
        }

        private void download_video_from_url(string url)
        {
            WebClient webClient = new WebClient();
            
            //webClient.DownloadFileAsync(new Uri(url), @current_working_directory + "\\" + makeTitleFileCompliant(youtube_video_title) + ".flv");
            nomeArquivo = makeTitleFileCompliant(youtube_video_title) + ".flv";
            webClient.DownloadFile(new Uri(url), @current_working_directory + "\\" + nomeArquivo);
        }

        // This method makes the YouTube title compliant as a filename

        public string makeTitleFileCompliant(string title_uncomp)
        {
                    return title_uncomp.Replace("\\", "").Replace("/", "").Replace("*", "").Replace(":", "").Replace("?", "").Replace("\"", "").Replace("<", "").Replace(">", "").Replace("|", "");

        }

    }
}
